package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"net/http"
	err2 "remote_cmd/error"
	"remote_cmd/models"
	"remote_cmd/result"
	"remote_cmd/utils"
)

type FileController struct {
	beego.Controller
}

func (c *FileController) File() {
	var file models.File
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &file)
	if err != nil {
		result.HttpResponse(http.StatusBadRequest, []byte("invalid requestBody"), c.Ctx)
		return
	}
	if !utils.IsValidIP(file.Ip) {
		result.HttpResponse(http.StatusBadRequest, []byte("Invalid IP"), c.Ctx)
		return
	}
	if !utils.IsValidFileOperationType(file.Type) {
		result.HttpResponse(http.StatusBadRequest, []byte("Invalid File Operation Type"), c.Ctx)
		return
	}
	if file.Type == models.ReadOnly {
		err = file.Cat()
	} else {
		err = file.Edit()
	}
	if err != nil {
		result.HttpResponse(http.StatusForbidden, []byte(err.Error()), c.Ctx)
		return
	}
	resMap := make(map[string]string)
	resMap["fileName"] = file.FileName
	resMap["content"] = file.ContentStr
	resByte, err := json.Marshal(resMap)
	if err != nil {
		result.HttpResponse(http.StatusInternalServerError, []byte(err.Error()), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, resByte, c.Ctx)
}

func (c *FileController) SyncFile() {
	var syncFile models.SyncFile
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &syncFile)
	if err != nil {
		result.HttpResponse(http.StatusBadRequest, []byte(err.Error()), c.Ctx)
		return
	}
	err = syncFile.SyncFile()
	errList, ok := err.(err2.ErrorList)
	if !ok {
		result.HttpResponse(http.StatusInternalServerError, []byte(errList.Error()), c.Ctx)
		return
	}
	if len(errList) != 0 {
		result.HttpResponse(http.StatusForbidden, []byte(errList.Error()), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, []byte("sync file success!"), c.Ctx)
}
